//
//  TL_CommentsTableViewCell.m
//  WXReader
//
//  Created by Andrew on 2018/5/27.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "TL_CommentsTableViewCell.h"
#import "TL_ReportAlertView.h"
#import "UIImageView+Utils.h"

#import "TLCommentMoreAlterView.h"

@implementation TL_CommentsTableViewCell {
    UIImageView *userAvatarImageView;   // 头像
    UILabel *nickNameLabel;     // 昵称
    
    UILabel *timeLabel;         //发布时间
    UIImageView *vipImageView;
    
    UILabel *replyNumLabel;
    UILabel *replyLabel;
    
    UIImageView *replyImageView;
    
    UIView *rbView;
    UILabel *rlab1;
    UILabel *rlab2;
    UILabel *rlab3;
    UILabel *rlab4;
    
    UIButton *moreBtn;
}

- (void)createSubviews {
    [super createSubviews];
    
    // 头像
    userAvatarImageView = [TL_UIFactory imageViewWithBackgroundColor:UIColor.clearColor image:HoldUserAvatar cornerRadius:34 / 2];
    [self.contentView addSubview:userAvatarImageView];
    
    [userAvatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).with.offset(kMoreHalfMargin);
        make.top.mas_equalTo(self.contentView.mas_top).with.offset(kHalfMargin);
        make.width.height.mas_equalTo(29);
    }];
    
    // 昵称
    nickNameLabel = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:SYSTEM_FONT(15) textColor:kBlackColor];
    [self.contentView addSubview:nickNameLabel];
    
    [nickNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(userAvatarImageView.mas_right).with.offset(kHalfMargin);
        make.right.mas_equalTo(self.contentView.mas_right).with.offset(- kMoreHalfMargin - kGeometricWidth(10, 138, 48));
        make.centerY.mas_equalTo(userAvatarImageView.mas_centerY);
        make.height.mas_equalTo(20);
    }];
    
    moreBtn = [[UIButton alloc] init];
    [moreBtn setImage:[UIImage imageNamed:@"more-h 1"] forState:UIControlStateNormal];
    [moreBtn addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView.mas_right).offset(-15);
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.centerY.mas_equalTo(userAvatarImageView.mas_centerY);
    }];
    
    vipImageView = [TL_UIFactory imageViewWithBackgroundColor:UIColor.clearColor image:[UIImage imageNamed:@"public_vip_select"] cornerRadius:0];
    [self.contentView addSubview:vipImageView];
    
    [vipImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(nickNameLabel.mas_right).offset(kQuarterMargin);
        make.centerY.mas_equalTo(nickNameLabel.mas_centerY);
        make.width.mas_equalTo(kGeometricWidth(10, 138, 48));
        make.height.mas_equalTo(10);
    }];
    
    replyLabel= [[UILabel alloc] init];
    replyLabel.textColor = RGB(77, 77, 75);
    replyLabel.font = MK_FONT_PFSC_Medium(14);
    replyLabel.textAlignment = NSTextAlignmentLeft;
    [self.contentView addSubview:replyLabel];
    [replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(userAvatarImageView.mas_right).with.offset(kHalfMargin);
        make.top.mas_equalTo(nickNameLabel.mas_bottom).offset(10);
        make.right.mas_equalTo(self.contentView.mas_right).with.offset(-kMargin);
    }];
    
    // 评论
    self.commentLabel = [TL_UIFactory label];
    self.commentLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - 2 * kMoreHalfMargin - kHalfMargin - 34;
    [self.contentView addSubview:self.commentLabel];

    [self.commentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(nickNameLabel.mas_left);
        make.right.mas_equalTo(self.contentView.mas_right).with.offset(- kMoreHalfMargin);
        make.top.mas_equalTo(replyLabel.mas_bottom).with.offset(kHalfMargin);
        make.height.mas_equalTo(10);
    }];

    // 举报
    UIButton *reportButton = [TL_UIFactory buttonWithTarget:self action:@selector(dzAction)];
    [reportButton setImage:[[UIImage imageNamed:@"like-1-unSelected"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    reportButton.contentEdgeInsets = UIEdgeInsetsMake(7.5, 7.5, 7.5, 7.5);
    reportButton.tintColor = RGB(153, 153, 153);
    [self.contentView addSubview:reportButton];
    
    [reportButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.commentLabel.mas_bottom).offset(kHalfMargin);
        make.right.equalTo(self.commentLabel.mas_right);
        make.width.height.mas_equalTo(30.0);
    }];
    reportButton.hidden = YES;
    
    replyNumLabel = [TL_UIFactory labelWithBackgroundColor:[UIColor clearColor] font:SYSTEM_FONT(10) textColor:RGB(153, 153, 153)];
    replyNumLabel.hidden = YES;
    [self.contentView addSubview:replyNumLabel];
    
    [replyNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.commentLabel.mas_bottom).offset(kHalfMargin);
        make.right.equalTo(self.commentLabel.mas_right).offset(-3);
        make.width.height.mas_equalTo(30.0);
    }];
    
    replyImageView = [TL_UIFactory imageViewWithBackgroundColor:[UIColor clearColor] image:[[UIImage imageNamed:@"like-1-unSelected"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] cornerRadius:0];
    replyImageView.tintColor = RGB(153, 153, 153);
    replyImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *replyTapGe = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dzAction)];
    [replyImageView addGestureRecognizer:replyTapGe];
    
    [self.contentView addSubview:replyImageView];
    
    [replyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(replyNumLabel.mas_left).with.offset(- kQuarterMargin);
        make.centerY.mas_equalTo(reportButton.mas_centerY);
        make.width.mas_equalTo(16);
        make.height.mas_equalTo(16);
    }];
    
    timeLabel = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:SYSTEM_FONT(12) textColor:RGB(153, 153, 153)];
    [self.contentView addSubview:timeLabel];
    
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.commentLabel.mas_left);
        make.right.mas_equalTo(replyImageView.mas_left).offset(- kHalfMargin);
        make.centerY.mas_equalTo(reportButton.mas_centerY);
        make.height.mas_equalTo(20);
    }];
    
    rbView = [TL_UIFactory viewWithBackgroundColor:[UIColor colorWithHexString:@"F9F9F9"] cornerRadius:0];
    [self.contentView addSubview:rbView];
    
    [rbView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(timeLabel.mas_bottom).offset(kHalfMargin);
        make.left.mas_equalTo(nickNameLabel);
        make.right.mas_equalTo(-kMoreHalfMargin);
        make.bottom.mas_equalTo(0);
    }];
    
    rlab1 = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:kMainFont textColor:kBlackColor];
    rlab1.userInteractionEnabled = YES;
    rlab1.tag = 100;
    [rbView addSubview:rlab1];

    [rlab1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kQuarterMargin);
        make.left.mas_equalTo(rbView).offset(kHalfMargin);
        make.right.mas_equalTo(rbView).offset(-kHalfMargin);
    }];
    
    rlab2 = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:kMainFont textColor:kBlackColor];
    rlab2.userInteractionEnabled = YES;
    rlab2.tag = 101;
    [rbView addSubview:rlab2];
    
    [rlab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(rlab1.mas_bottom).offset(kQuarterMargin);
        make.left.right.mas_equalTo(rlab1);
    }];
    
    rlab3 = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:kMainFont textColor:kBlackColor];
    rlab3.userInteractionEnabled = YES;
    rlab3.tag = 102;
    [rbView addSubview:rlab3];
    
    [rlab3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(rlab2.mas_bottom).offset(kQuarterMargin);
        make.left.right.mas_equalTo(rlab2);
    }];
    
    rlab4 = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:kMainFont textColor:kBlackColor];
    rlab4.userInteractionEnabled = YES;
    rlab4.tag = 103;
    rlab4.textAlignment = NSTextAlignmentRight;
    rlab4.text = @"View all >";
    rlab4.hidden = NO;
    rlab4.font = MK_FONT_PFSC_Medium(14);
    rlab4.textColor = [UIColor colorWithHexString:@"#51ACE0"];
    [rlab4 setBackgroundColor:[UIColor colorWithHexString:@"F9F9F9"]];
    [self.contentView addSubview:rlab4];
    
    [rlab4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(rbView.mas_bottom).offset(kQuarterMargin);
        make.left.right.mas_equalTo(rbView);
        make.bottom.mas_equalTo(-kQuarterMargin);
    }];
    
    [self.cellLine mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(34 + 2 * kMoreHalfMargin);
    }];
    
    [self addGestAction:rlab1];
    [self addGestAction:rlab2];
    [self addGestAction:rlab3];
    [self addGestAction:rlab4];
    
}
- (void)addGestAction:(UILabel*)label{
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestAction:)];
    [label addGestureRecognizer:tapGes];
    
}
- (void)tapGestAction:(UITapGestureRecognizer *)tapGest {
    
    UILabel *lab = (UILabel*)tapGest.view;
    
    NSLog(@"%ld",lab.tag);
    
    int index = (int)lab.tag - 100;
    
    if (index == 3) {
        
        if (self.gotoCommentDetailsBlock) {
            self.gotoCommentDetailsBlock();
        }
        
    }else{
        
        if (self.replyReplyBlock) {
            self.replyReplyBlock(self.commentModel.replay_commons[index]);
        }
    }
    
    
}

- (void)setCommentModel:(TL_CommentsDetailModel *)commentModel {
    if (!commentModel) {
        return;
    }
    
    _commentModel = commentModel;
    
    if (commentModel.reply_num > 3) {
        rlab4.hidden = NO;
        rlab4.text = [NSString stringWithFormat:@"View all(%ld) >",commentModel.reply_num];
    } else {
        rlab4.hidden = YES;
        rlab4.text = [NSString stringWithFormat:@"View all(%ld) >",commentModel.reply_num];
    }
    [userAvatarImageView setUserAvatarWithURLString:commentModel.headPic];

    nickNameLabel.text = [TL_UtilsHelper formatStringWithObject:commentModel.nickname];

    vipImageView.hidden = !commentModel.is_vip;

    self.commentLabel.attributedText = [[NSAttributedString alloc] initWithString:commentModel.content?:@"" attributes:@{NSForegroundColorAttributeName : kBlackColor}];
    [self.commentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.commentLabel.w_textHeight + kHalfMargin);
    }];
        
    timeLabel.text = [NSDate convert2LocalTimeWithString:[NSString stringWithFormat:@"%@",commentModel.time?:@""] andWithFormatter:@"MM-dd HH:mm"];
    
//    replyLabel.text = commentModel.toNickName;
    
    if (![commentModel.toNickName isEqualToString:@""] && commentModel.toNickName) {
        
        NSString *str = [NSString stringWithFormat:@"reply %@", commentModel.toNickName];
        
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName : SYSTEM_FONT(12), NSForegroundColorAttributeName : kBlackColor}];
        
        attributedStr.lineBreakMode = NSLineBreakByTruncatingTail;
        [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"51ace0"] range:NSMakeRange(6, commentModel.toNickName.length)];
        
        replyLabel.attributedText = attributedStr;
    }
    
//    if (commentModel.reply_num > 0) {
//        replyImageView.hidden = NO;
//        replyNumLabel.hidden = NO;
//        replyNumLabel.text = [TL_UtilsHelper formatStringWithInteger:commentModel.reply_num];
//    } else {
//        replyImageView.hidden = YES;
//        replyNumLabel.hidden = YES;
//    }
    
    replyNumLabel.text = [TL_UtilsHelper formatStringWithInteger:commentModel.like_num];
    replyNumLabel.hidden = NO;
    [replyNumLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(replyNumLabel.w_textWidth);
    }];   

    rlab1.attributedText = [[NSAttributedString alloc] initWithString:@""];
    rlab1.numberOfLines = self.commentLabel.numberOfLines;
    
    rlab2.attributedText = [[NSAttributedString alloc] initWithString:@""];
    rlab2.numberOfLines = self.commentLabel.numberOfLines;

    rlab3.attributedText = [[NSAttributedString alloc] initWithString:@""];
    rlab3.numberOfLines = self.commentLabel.numberOfLines;
    
    if (commentModel.likeStatus) {
        [replyImageView setImage:[UIImage imageNamed:@"like-1-selected"]];
    }else{
        [replyImageView setImage:[UIImage imageNamed:@"like-1-unSelected"]];
    }
    
    if ((commentModel.replay_commons.count == 0) || self.isReplyList) {
        rbView.hidden = YES;
        [rbView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
        }];
        
        [rlab1 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
        }];
        
        [rlab2 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(rlab1.mas_bottom).offset(0);
        }];
        
        [rlab3 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(rlab2.mas_bottom).offset(0);
            make.bottom.mas_equalTo(0);
        }];
    } else {
        rbView.hidden = NO;
        [rbView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
        }];
        [rlab1 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kQuarterMargin);
        }];
        
        [rlab2 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(rlab1.mas_bottom).offset(0);
        }];
        
        [rlab3 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(rlab2.mas_bottom).offset(0);
//            make.bottom.mas_equalTo(-kQuarterMargin);
        }];
        [rlab4 mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(rlab3.mas_bottom).offset(0);
            make.bottom.mas_equalTo(-kQuarterMargin);
        }];
        
        for (int i = 0; i < commentModel.replay_commons.count; i++) {
            TL_CommentsDetailModel *replyModel = [commentModel.replay_commons wx_objectOrNilAtIndex:i];
            
            NSString *str = [NSString stringWithFormat:@"%@:%@", replyModel.nickname,replyModel.content];
            if (![replyModel.toNickName isEqualToString:@""] && replyModel.toUserCardId != replyModel.uid) {
                str = [NSString stringWithFormat:@"%@ reply %@:%@", replyModel.nickname,replyModel.toNickName,replyModel.content];
            }
            
            NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName : SYSTEM_FONT(12), NSForegroundColorAttributeName : kBlackColor}];
            
            attributedStr.lineBreakMode = NSLineBreakByTruncatingTail;
            [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"51ace0"] range:NSMakeRange(0, replyModel.nickname.length+1)];
            if (![replyModel.toNickName isEqualToString:@""] && replyModel.toUserCardId != replyModel.uid) {
                
                [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"51ace0"] range:NSMakeRange([NSString stringWithFormat:@"%@ replay ",replyModel.nickname].length-1, replyModel.toNickName.length)];
            }else{
                
                [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"51ace0"] range:NSMakeRange(0, replyModel.toNickName.length+1)];
                
            }
            
            switch (i) {
                case 0: {
                    rlab1.attributedText = attributedStr;
                }
                    break;
                case 1:{
                    rlab2.attributedText = attributedStr;
                    [rlab2 mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.mas_equalTo(rlab1.mas_bottom).offset(kQuarterMargin);
                    }];
                }
                    break;
                case 2:
                {
                    rlab3.attributedText = attributedStr;
                    [rlab3 sizeToFit];
                    if (commentModel.reply_num > 3) {
                        rlab4.hidden = NO;
                        [rlab4 mas_remakeConstraints:^(MASConstraintMaker *make) {
                            make.top.mas_equalTo(rlab3.mas_bottom).offset(kQuarterMargin+2);
                            make.left.right.mas_equalTo(rbView);
                            make.height.mas_offset(20);
                            make.bottom.mas_equalTo(-kQuarterMargin); // 关键修改：明确底部约束
                        }];
                    } else {
                        rlab4.hidden = YES;
                        [rlab4 mas_remakeConstraints:^(MASConstraintMaker *make) {
                            make.top.mas_equalTo(rlab3.mas_bottom).offset(kQuarterMargin+2);
                            make.left.right.mas_equalTo(rbView);
                            make.height.mas_offset(0);
                            make.bottom.mas_equalTo(-kQuarterMargin); // 关键修改：明确底部约束
                        }];
                    }
                }
                    break;
                default: 
                    break;
            }
            if (i == 2) {
                break;
            }
        }
    }
}

- (void)setIsPreview:(BOOL)isPreview lastRow:(BOOL)lastRow {
    if (isPreview && !lastRow) {
        [self.cellLine mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.commentLabel);
            make.height.mas_equalTo(kCellLineHeight);
            make.right.equalTo(self.contentView);
            make.bottom.mas_equalTo(self.contentView.mas_bottom).with.offset( - kCellLineHeight);
        }];
        return;
    }
    
    if (isPreview && lastRow) {
        [self.cellLine mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(userAvatarImageView);
            make.height.mas_equalTo(kCellLineHeight);
            make.right.equalTo(self.contentView);
            make.bottom.mas_equalTo(self.contentView.mas_bottom).with.offset( - kCellLineHeight);
        }];
        return;
    }
}

/// 举报评论
- (void)reportEvent {
    TL_ReportAlertView *sheetView = [[TL_ReportAlertView alloc] init];
    sheetView.book_id = self.commentModel.book_id;
    sheetView.comment_id = self.commentModel.comment_id;
    sheetView.productionType = self.productionType;
    [sheetView showAlertView];
    
    MK_WEAK_SELF;
    sheetView.reportSuccessBlock = ^{
//        if (weakSelf.deleteCommentBlock) {
//            weakSelf.deleteCommentBlock(weakSelf.commentModel);
//        }
    };
}
- (void)dzAction{
    
    [APIManager sendPostRequest:[APIURLManager likeGoods] parameters:@{@"commentId":@(self.commentModel.comment_id)} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            self.commentModel.likeStatus = !self.commentModel.likeStatus;
            
            if (self.commentModel.likeStatus) {
                [replyImageView setImage:[UIImage imageNamed:@"like-1-selected"]];
                self.commentModel.like_num = self.commentModel.like_num+1;
                replyNumLabel.text = [TL_UtilsHelper formatStringWithInteger:self.commentModel.like_num];
                replyNumLabel.textColor = kMainColor;
            }else{
                [replyImageView setImage:[UIImage imageNamed:@"like-1-unSelected"]];
                self.commentModel.like_num = self.commentModel.like_num-1;
                replyNumLabel.text = [TL_UtilsHelper formatStringWithInteger:self.commentModel.like_num];
                replyNumLabel.textColor = [UIColor hex_999999];
            }
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
    
    
}

- (void)replyEvent {
    if (self.replyCommentBlock) {
        self.replyCommentBlock(self.commentModel);
    }
}

- (void)setIsReplyList:(BOOL)isReplyList {
    _isReplyList = isReplyList;
}
- (void)moreAction{
    
    TLCommentMoreAlterView *view = [TLCommentMoreAlterView createViewWithCommentId:self.commentModel.comment_id];
    
    [view showAction];
    
    MJWeakSelf
    view.returnCommentIdBlock = ^(NSInteger commentId, int type) {
        
        if (weakSelf.deleteCommentBlock) {
            weakSelf.deleteCommentBlock(weakSelf.commentModel,type);
        }
    };
    
}
@end
